// 初始化购物车
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// 商品数据
const products = [
    { id: 1, name: '汉堡', price: 20, category: 'food', image: 'images/product1.jpg' },
    { id: 2, name: '可乐', price: 5, category: 'drink', image: 'images/product2.jpg' },
    { id: 3, name: '披萨', price: 50, category: 'food', image: 'images/product3.jpg' },
    { id: 4, name: '果汁', price: 10, category: 'drink', image: 'images/product4.jpg' }
];

// // 初始化显示全部商品
function renderProducts(category = 'all') {
    const productList = document.querySelector('.product-list');
    productList.innerHTML = '';

    const filteredProducts = category === 'all' ? products : products.filter(product => product.category === category);

    filteredProducts.forEach(product => {
        const productDiv = document.createElement('div');
        productDiv.className = 'product';
        productDiv.dataset.id = product.id;
        productDiv.dataset.price = product.price;
        productDiv.innerHTML = `
            <!-- 修改图片 src 属性为 noImg.png -->
            <img src="images/noImg.png" alt="${product.name}">
            <div class="product-info">
                <h3>${product.name}</h3>
                <p>价格: ${product.price} 元/份</p>
                <div class="product-actions">
                    <div class="quantity-control">
                        <button class="minus">-</button>
                        <input type="number" class="quantity" value="0" min="0">
                        <button class="plus">+</button>
                    </div>
                    <button class="add-to-cart">加入购物车</button>
                </div>
            </div>
        `;
        productList.appendChild(productDiv);
    });
}
// 加入购物车
document.querySelectorAll('.add-to-cart').forEach(button => {
    button.addEventListener('click', () => {
        const product = button.closest('.product');
        const id = product.dataset.id;
        const name = product.querySelector('h3').textContent;
        const price = parseFloat(product.dataset.price);
        const quantity = parseInt(product.querySelector('.quantity').value);
        console.log(quantity)
        if (quantity > 0) {
            // const existingItem = cart.find(item => item.id === id);
            // if (existingItem) {
            //     existingItem.quantity += quantity;
            // } else {
            //     cart.push({ id, name, price, quantity });
            // }
            // localStorage.setItem('cart', JSON.stringify(cart));
            // alert('商品已加入购物车');
            // product.querySelector('.quantity').value = 0;
            $.ajax({
                type: "POST",
                url:"/placeOrder",
                data:{ id: id, quantity:quantity,price:price },
                async: false,
                error: function(request) {
                    alert("程序出错，请联系管理员");
                },
                success: function(data) {
                    if (data.code===200){
                        window.location.href = '/orderSuccess';
                    }else {
                        window.location.href = data.message;
                        //alert(data.message);
                    }
                }
            });
        }
    });
});
    // 商品数量加减
document.addEventListener('DOMContentLoaded', function() {
    // 为所有减号按钮添加点击事件监听器
    const minusButtons = document.querySelectorAll('.minus');
    minusButtons.forEach(button => {
        button.addEventListener('click', function() {
            const quantityInput = this.nextElementSibling;
            let currentValue = parseInt(quantityInput.value, 10);
            if (currentValue > 1) {
                quantityInput.value = currentValue - 1;
            }
        });
    });

    // 为所有加号按钮添加点击事件监听器
    const plusButtons = document.querySelectorAll('.plus');
    plusButtons.forEach(button => {
        button.addEventListener('click', function() {
            const quantityInput = this.previousElementSibling;
            let currentValue = parseInt(quantityInput.value, 10);
            quantityInput.value = currentValue + 1;
        });
    });
});
// 分类按钮点击事件
document.querySelectorAll('.category-btn').forEach(button => {
    button.addEventListener('click', () => {
        document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
        const category = button.dataset.category;
        // renderProducts(category);
    });
});

// 幻灯片功能
if (window.location.pathname.includes('index.html')) {
    const slides = document.querySelector('.slides');
    let currentSlide = 0;
    let autoPlayInterval;

    function showSlide(n) {
        currentSlide = (n + 3) % 3;
        slides.style.transform = `translateX(-${currentSlide * 33.3333}%)`;
    }

    function startAutoPlay() {
        autoPlayInterval = setInterval(() => {
            showSlide(currentSlide + 1);
        }, 1000);
    }

    function stopAutoPlay() {
        clearInterval(autoPlayInterval);
    }

    // 鼠标悬停时暂停自动播放
    slides.addEventListener('mouseover', stopAutoPlay);
    slides.addEventListener('mouseout', startAutoPlay);

    // 初始化自动播放
    startAutoPlay();
}

// 购物车页面初始化
if (window.location.pathname.includes('cart.html')) {
    const cartItemsDiv = document.querySelector('.cart-items');
    const totalPriceSpan = document.getElementById('total-price');

    function renderCart() {
        if (cartItemsDiv) {
            cartItemsDiv.innerHTML = ''; 
            let total = 0;

            cart.forEach(item => {
                const cartItemDiv = document.createElement('div');
                cartItemDiv.className = 'cart-item';
                cartItemDiv.innerHTML = `
                    <span>${item.name}</span>
                    <span>单价: ${item.price} 元</span>
                    <span>数量: ${item.quantity}</span>
                    <span>小计: ${item.price * item.quantity} 元</span>
                `;
                cartItemsDiv.appendChild(cartItemDiv);
                total += item.price * item.quantity;
            });

            if (totalPriceSpan) {
                totalPriceSpan.textContent = total;
            }
        } else {
            console.error('未找到 .cart-items 元素，请检查 HTML 结构');
        }
    }

    renderCart();

    // 为去支付按钮添加点击事件
    const payBtn = document.querySelector('.bottom-payment-bar .pay-btn');
    if (payBtn) {
        payBtn.addEventListener('click', () => {
                window.location.href = 'order-success.html';
            // if (cart.length > 0) {
            //     // 保存购物车数据到 localStorage
            //     localStorage.setItem('orderItems', JSON.stringify(cart));
            //     // 结算成功跳转到下单成功页面
            //     window.location.href = 'order-success.html';
            //     cart = [];
            //     localStorage.setItem('cart', JSON.stringify(cart));
            //     renderCart();
            // } else {
            //     alert('购物车为空，请先添加商品');
            // }
        });
    }
}

// 初始化渲染商品
// renderProducts();

// 检查 DOM 是否加载完成
document.addEventListener('DOMContentLoaded', function() {
    const payBtn = document.querySelector('.bottom-payment-bar .pay-btn');
    if (payBtn) {
        payBtn.addEventListener('click', function() {
            window.location.href = 'order-success.html';
        });
    }

    // 修正选择器
    // const targetElement = document.querySelector('.order-details');
    // if (targetElement) {
    //     targetElement.innerHTML = '这是修改后的内容';
    // } else {
    //     console.error('未找到匹配的元素，请检查选择器或 HTML 结构');
    // }
});